package com.example.attendance_back.config;

import cn.hutool.json.JSON;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.example.attendance_back.model.ResponseMessage;
import com.example.attendance_back.utils.JWTUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.netty.util.internal.StringUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;

@Component
public class TokenInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request
            , HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("token");
        if (StringUtil.isNullOrEmpty(token)) {
            try {
                throw new RuntimeException("尚未登录，请重新登录");
            } catch (Exception e) {
                System.out.println("尚未登录，请重新登录");
                /**
                 *  jaskson 是springboot 默认的json工具
                 *  (fastjson)
                 * */
                outRes(response);
                return false;
            }
        } else {
            try {
                JWTUtils.verifyToken(token);
            } catch (JWTVerificationException e) {

                System.out.println("token 异常");
                outRes(response);

                return false;
            }

        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    private void outRes(HttpServletResponse response) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        ResponseMessage responseMessage = new ResponseMessage();
        responseMessage.setSuccess(false);
        String res = objectMapper.writeValueAsString(responseMessage);

        /**
         *   相当于 在controller retrun ''
         * */
        response.getWriter().println(res);
    }
}
